package com.zhangzhan.aspect;

import com.alibaba.fastjson.JSON;
import com.zhangzhan.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 张一恒
 * @version 1.0
 * @description: AOP日志
 * @date 2022/12/4 16:37
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    //切点方法 根据注解
    @Pointcut("@annotation(com.zhangzhan.annotation.SystemLog)")
    public void pt() {}

    /**
     * @description 环绕通知
     * @param joinPoint
     * @return java.lang.Object
     * @author 31115
     * @date 2022/12/4 16:43
     */
    @Around("pt()")
    public Object printLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Object ret;
        try {

            handleBefore(joinPoint);

            //目标方法的调用
            ret = joinPoint.proceed();

            handleAfter(ret);
        } finally {
            // 结束后换行
            log.info("=======End=======" + System.lineSeparator());
        }

        return ret;
    }

    //执行后日志打印
    private void handleAfter(Object ret) {

        // 打印出参
        log.info("Response       : {}", JSON.toJSONString(ret));

    }

    //执行前日志打印
    private void handleBefore(ProceedingJoinPoint joinPoint) {

        //获取当前方法的url
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();

        SystemLog businessName = getSystemLog(joinPoint);

        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",url);
        // 打印描述信息
        log.info("BusinessName   : {}", businessName.BusinessName());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
                ((MethodSignature) joinPoint.getSignature()).getMethod().getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));

    }

    /**
     * @description 获取方法对象，取自定义注解里的参数
     * @param joinPoint
     * @return com.zhangzhan.annotation.SystemLog
     * @author 31115
     * @date 2022/12/4 17:08
     */
    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        //((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(SystemLog.class).BusinessName()
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法对象 获取方法的注解对象 getAnnotation（）
        SystemLog systemLog = signature.getMethod().getAnnotation(SystemLog.class);

        return systemLog;
    }

}
